package com.erp.gather.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Dict;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.gather.domain.ErpCollectProductCategory;
import com.erp.gather.domain.ErpProductArea;
import com.erp.gather.domain.bo.ErpSellerCollectProductBo;
import com.erp.gather.mapper.*;
import com.erp.gather.service.*;
import com.erp.gather.utils.ChatGptUtils;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.CommonUtils;
import com.ruoyi.common.core.utils.JsonUtils;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.gather.api.domain.*;
import com.erp.gather.domain.vo.ErpSellerCollectProductExpandVo;
import com.erp.gather.domain.vo.ErpSellerCollectProductSkuVo;
import com.erp.gather.domain.vo.ErpSellerCollectProductVo;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.domain.SysOss;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.domain.dto.OssUrlDto;
import com.ruoyi.system.api.domain.vo.SysOssVo;
import com.sun.xml.bind.v2.TODO;
import lombok.RequiredArgsConstructor;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 个人采集商品Service业务层处理
 *
 * @author erp
 * @date 2023-06-20
 */
@RequiredArgsConstructor
@Service
public class ErpSellerCollectProductServiceImpl implements IErpSellerCollectProductService {

    private final ErpSellerCollectProductMapper baseMapper;
    private final ErpCollectProductCategoryMapper collectProductCategoryMapper;
    private final ErpSellerCollectProductSkuMapper erpSellerCollectProductSkuMapper;
    private final ErpSellerCollectProductExpandMapper erpSellerCollectProductExpandMapper;

    @Resource
    RemoteFileService remoteFileService;

    private final ErpCollectProductMapper collectProductMapper;
    private final ErpCollectProductSkuMapper collectProductSkuMapper;
    private final ErpCollectProductExpandMapper collectProductExpandMapper;
    private final IErpCollectProductExpandService erpCollectProductExpandService;
    private final IErpCollectProductSkuPriceService iErpCollectProductSkuPriceService;
    private final IErpCollectProductService iErpCollectProductService;
    private final IErpCollectProductTranslateTaskService iErpCollectProductTranslateTaskService;
    private final AliexpressCategoryServiceImpl aliexpressCategoryServiceImpl;
    private final ErpProductAreaMapper erpProductAreaMapper;
//    private final IErpProductFreightService iErpProductFreightService;
    private final ErpCollectProductSkuPriceMapper collectProductSkuPriceMapper;

    private final ErpSellerProductMapper erpSellerProductMapper;
    private final ErpSellerProductSkuMapper erpSellerProductSkuMapper;
    private final ErpSellerProductExpandMapper erpSellerProductExpandMapper;
    private final ErpSellerStoreProductMapper erpSellerStoreProductMapper;
    private final ErpSellerStoreProductSkuMapper erpSellerStoreProductSkuMapper;
    private final ErpSellerStoreProductExpandMapper erpSellerStoreProductExpandMapper;

    private final IErpSellerStoreProductService iErpSellerStoreProductService;

//    private final DictService dictService;

//    private final SysUserMapper sysUserMapper;
//    private final SysOssServiceImpl sysOssService;
//    private final IErpCollectProductFreightTaskService erpCollectProductFreightTaskService;
//    private final ErpSellerStoreFreightTemplateMapper erpSellerStoreFreightTemplateMapper;

//	private final IAeProductService iAeProductService;

    /**
     * 查询个人采集商品
     */
    @Override
    public ErpSellerCollectProductVo queryById(Long id) {
        ErpSellerCollectProductVo erpCollectProductVo = baseMapper.selectVoById(id);
        // 获取sku
        List<ErpSellerCollectProductSkuVo> productVoSkus = erpSellerCollectProductSkuMapper
                .selectVoList(new LambdaQueryWrapper<ErpSellerCollectProductSku>()
                        .eq(ErpSellerCollectProductSku::getCollectProductId, id));
        erpCollectProductVo.setSkuList(productVoSkus);

        // 获取产品扩展表
        ErpSellerCollectProductExpandVo collectProductExpandVo = erpSellerCollectProductExpandMapper
                .selectVoOne(new LambdaQueryWrapper<ErpSellerCollectProductExpand>()
                        .eq(ErpSellerCollectProductExpand::getCollectProductId, id));
        erpCollectProductVo.setExpand(collectProductExpandVo);
        return erpCollectProductVo;
    }

    /**
     * 查询个人采集商品列表
     */
    @Override
    public TableDataInfo<ErpSellerCollectProductVo> queryPageList(ErpSellerCollectProductBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpSellerCollectProduct> lqw = buildQueryWrapper(bo);

        List<SFunction<ErpSellerCollectProduct, ?>> columns = new ArrayList<>();
        columns.add(ErpSellerCollectProduct::getId);
        columns.add(ErpSellerCollectProduct::getSubject);
        columns.add(ErpSellerCollectProduct::getImageURLs);
        columns.add(ErpSellerCollectProduct::getWhite);
        columns.add(ErpSellerCollectProduct::getCategoryId);
        columns.add(ErpSellerCollectProduct::getCollectUrl);
        columns.add(ErpSellerCollectProduct::getProductPrice);
        columns.add(ErpSellerCollectProduct::getDelFlag);
        columns.add(ErpSellerCollectProduct::getCollectUserId);
        columns.add(ErpSellerCollectProduct::getMarketing);
        columns.add(ErpSellerCollectProduct::getDetailImg);
        lqw.select(columns);

        Page<ErpSellerCollectProductVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        result.getRecords().forEach(vo -> {

            Long categoryId = vo.getCategoryId();
            if (categoryId != null) {
                ErpCollectProductCategory category = collectProductCategoryMapper.selectById(categoryId);
                if (category != null)
                    vo.setCategoryName(category.getName());
            }

            // 获取sku
//			List<ErpSellerCollectProductSkuVo> productVoSkus = erpSellerCollectProductSkuMapper
//					.selectVoList(new LambdaQueryWrapper<ErpSellerCollectProductSku>()
//							.eq(ErpSellerCollectProductSku::getCollectProductId, vo.getId()));
//			vo.setSkuList(productVoSkus);

            // 获取产品扩展表
            LambdaQueryWrapper<ErpSellerCollectProductExpand> expandlqw = new LambdaQueryWrapper<ErpSellerCollectProductExpand>();

            List<SFunction<ErpSellerCollectProductExpand, ?>> expandcolumns = new ArrayList<>();
            expandcolumns.add(ErpSellerCollectProductExpand::getId);
            expandcolumns.add(ErpSellerCollectProductExpand::getProductStatus);
            expandcolumns.add(ErpSellerCollectProductExpand::getEditStatus);
            expandcolumns.add(ErpSellerCollectProductExpand::getIsOptimize);
            expandcolumns.add(ErpSellerCollectProductExpand::getIsFreight);
            expandcolumns.add(ErpSellerCollectProductExpand::getIsTranslate);
            expandcolumns.add(ErpSellerCollectProductExpand::getIsUploadTest);
            expandcolumns.add(ErpSellerCollectProductExpand::getClassifyLabel);
            expandcolumns.add(ErpSellerCollectProductExpand::getIsAutoOptimize);
            expandcolumns.add(ErpSellerCollectProductExpand::getAutoOptimizeRemark);
            expandcolumns.add(ErpSellerCollectProductExpand::getIsViola);
            expandcolumns.add(ErpSellerCollectProductExpand::getViolaText);
            expandlqw.eq(ErpSellerCollectProductExpand::getCollectProductId, vo.getId());
            ErpSellerCollectProductExpandVo collectProductExpandVo = erpSellerCollectProductExpandMapper
                    .selectVoOne(expandlqw);
            vo.setExpand(collectProductExpandVo);

            //TODO 改为内部类调用
//            SysUser sysUser = sysUserMapper.selectUserById(vo.getCollectUserId());
            SysUser sysUser = null;
            vo.setCollectUserName(sysUser == null ? "" : sysUser.getNickName());

        });

        return TableDataInfo.build(result);
    }

    /**
     * 查询个人采集商品列表
     */
    @Override
    public List<ErpSellerCollectProductVo> queryList(ErpSellerCollectProductBo bo) {
        LambdaQueryWrapper<ErpSellerCollectProduct> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpSellerCollectProduct>  buildQueryWrapper(ErpSellerCollectProductBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpSellerCollectProduct> lqw = Wrappers.lambdaQuery();

        if (bo.getCollectUserId() != null) {
            lqw.eq(bo.getCollectUserId() != null, ErpSellerCollectProduct::getCollectUserId, bo.getCollectUserId());
        } else {
            lqw.eq(ErpSellerCollectProduct::getCollectUserId, SecurityUtils.getUserId());
        }
        lqw.eq(bo.getId() != null, ErpSellerCollectProduct::getId, bo.getId());
//		lqw.eq(bo.getCategoryId() != null, ErpSellerCollectProduct::getCategoryId, bo.getCategoryId());
        lqw.eq(StringUtils.isNotBlank(bo.getImageURLs()), ErpSellerCollectProduct::getImageURLs, bo.getImageURLs());
        lqw.eq(StringUtils.isNotBlank(bo.getSubject()), ErpSellerCollectProduct::getSubject, bo.getSubject());
        lqw.eq(StringUtils.isNotBlank(bo.getWhite()), ErpSellerCollectProduct::getWhite, bo.getWhite());
        lqw.eq(StringUtils.isNotBlank(bo.getMarketing()), ErpSellerCollectProduct::getMarketing, bo.getMarketing());
        lqw.eq(StringUtils.isNotBlank(bo.getMedia()), ErpSellerCollectProduct::getMedia, bo.getMedia());
        lqw.eq(StringUtils.isNotBlank(bo.getCollectProductPrice()), ErpSellerCollectProduct::getCollectProductPrice,
                bo.getCollectProductPrice());
        lqw.eq(StringUtils.isNotBlank(bo.getProductPrice()), ErpSellerCollectProduct::getProductPrice,
                bo.getProductPrice());
        lqw.eq(StringUtils.isNotBlank(bo.getMobileDetail()), ErpSellerCollectProduct::getMobileDetail,
                bo.getMobileDetail());
        lqw.eq(bo.getPackageLength() != null, ErpSellerCollectProduct::getPackageLength, bo.getPackageLength());
        lqw.eq(StringUtils.isNotBlank(bo.getPackageWidth()), ErpSellerCollectProduct::getPackageWidth,
                bo.getPackageWidth());
        lqw.eq(bo.getPackageHeight() != null, ErpSellerCollectProduct::getPackageHeight, bo.getPackageHeight());
        lqw.eq(StringUtils.isNotBlank(bo.getGrossWeight()), ErpSellerCollectProduct::getGrossWeight,
                bo.getGrossWeight());
        lqw.eq(bo.getProductUnit() != null, ErpSellerCollectProduct::getProductUnit, bo.getProductUnit());
        lqw.eq(StringUtils.isNotBlank(bo.getCustomAttributes()), ErpSellerCollectProduct::getCustomAttributes,
                bo.getCustomAttributes());
        lqw.eq(StringUtils.isNotBlank(bo.getDetail()), ErpSellerCollectProduct::getDetail, bo.getDetail());
        lqw.eq(StringUtils.isNotBlank(bo.getDetailImg()), ErpSellerCollectProduct::getDetailImg, bo.getDetailImg());
        lqw.eq(bo.getSizechartId() != null, ErpSellerCollectProduct::getSizechartId, bo.getSizechartId());
        lqw.eq(StringUtils.isNotBlank(bo.getModeSizeChartList()), ErpSellerCollectProduct::getModeSizeChartList,
                bo.getModeSizeChartList());
        lqw.eq(StringUtils.isNotBlank(bo.getCollectUrl()), ErpSellerCollectProduct::getCollectUrl, bo.getCollectUrl());
        lqw.eq(bo.getCollectUserId() != null, ErpSellerCollectProduct::getCollectUserId, bo.getCollectUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getRevision()), ErpSellerCollectProduct::getRevision, bo.getRevision());

        // 价格区间查询
        if (StringUtils.isNotEmpty(bo.getProductPriceMin()))
            lqw.ge(ErpSellerCollectProduct::getProductPrice, bo.getProductPriceMin());
        if (StringUtils.isNotEmpty(bo.getProductPriceMax()))
            lqw.le(ErpSellerCollectProduct::getProductPrice, bo.getProductPriceMax());

        // 商品类目
        lqw.apply(bo.getCategoryId() != null,
                " category_id in (SELECT id FROM `erp_collect_product_category` WHERE id = " + bo.getCategoryId()
                        + " OR FIND_IN_SET( " + bo.getCategoryId() + " , ancestors ))");

        String expandSql = "";
        // 关键词
        String keyword = bo.getKeyword();
        if (StringUtils.isNotEmpty(keyword)) {
//			lqw.apply(
//					" id in (SELECT seller_collect_product_id FROM erp_seller_collect_product_expand WHERE keyword like '%"
//							+ keyword + "%')");
            expandSql += " and keyword like '%" + keyword + "%' ";
        }

        String classifyLabel = bo.getClassifyLabel();
        if (StringUtils.isNotEmpty(classifyLabel)) {
            expandSql += " and classify_label like '%" + classifyLabel + "%' ";
        }

        // 是否为品牌（0是 1否）
        Integer isBrand = bo.getIsBrand();
        if (isBrand != null) {
            if (isBrand.equals(0)) {
//				lqw.apply(
//						" id in (SELECT seller_collect_product_id FROM erp_seller_collect_product_expand WHERE brand_id IS NOT NULL)");
                expandSql += " and brand_id IS NOT NULL ";
            } else {
//				lqw.apply(
//						" id in (SELECT seller_collect_product_id FROM erp_seller_collect_product_expand WHERE brand_id IS NULL)");
                expandSql += " and brand_id IS NULL ";
            }
        }

        // 品牌id
        String brandId = bo.getBrandId();
        if (brandId != null) {
//			lqw.apply(
//					" id in (SELECT seller_collect_product_id FROM erp_seller_collect_product_expand WHERE brand_id in( "
//							+ brandId + "))");
            expandSql += " and brand_id in( " + brandId + ") ";
        }

        Integer isUploadTest = bo.getIsUploadTest();
        // 是否已发布测试
        if (isUploadTest != null) {
//			lqw.apply(
//					" id in (SELECT seller_collect_product_id FROM erp_seller_collect_product_expand WHERE is_upload_test = "
//							+ isUploadTest + ")");
            expandSql += " and is_upload_test = " + isUploadTest + " ";
        }

        // 是否为已编辑
        Integer isEdit = bo.getIsEdit();
        if (isEdit != null) {
//			lqw.apply(
//					" id in (SELECT seller_collect_product_id FROM erp_seller_collect_product_expand WHERE edit_status = "
//							+ isEdit + ")");
            expandSql += " and edit_status = " + isEdit + " ";
        }

        // 是否是自动获取类目
        Integer isAutoOptimize = bo.getIsAutoOptimize();
        if (isAutoOptimize != null) {
            expandSql += " and is_auto_optimize = " + isAutoOptimize + " ";
        }
        // 是否为已运费试算
        Integer isFreight = bo.getIsFreight();
        if (isFreight != null) {
//			lqw.apply(
//					" id in (SELECT seller_collect_product_id FROM erp_seller_collect_product_expand WHERE is_freight = "
//							+ isFreight + ")");
            expandSql += " and is_freight = " + isFreight + " ";
        }

        // 是否为已翻译
        Integer isTranslate = bo.getIsTranslate();
        if (isTranslate != null) {
//			lqw.apply(
//					" id in (SELECT seller_collect_product_id FROM erp_seller_collect_product_expand WHERE is_translate = "
//							+ isTranslate + ")");
            expandSql += " and is_translate = " + isTranslate + " ";
        }

        // 添加expandSql
        if (StringUtils.isNotEmpty(expandSql)) {
            expandSql = expandSql.substring(4);
            lqw.apply(" id in (SELECT collect_product_id FROM erp_collect_product_expand WHERE " + expandSql + ")");
        }

        // 是否为采集商品（0是 1否）
        Integer isCollect = bo.getIsCollect();
        if (isCollect != null) {
            if (isCollect.equals(0))
                lqw.isNotNull(ErpSellerCollectProduct::getCollectUrl);
            else
                lqw.isNull(ErpSellerCollectProduct::getCollectUrl);
        }

        // skuCode
        String skuCode = bo.getSkuCode();
        if (StringUtils.isNotEmpty(skuCode)) {
            lqw.apply(" id in (SELECT collect_product_id FROM erp_collect_product_sku WHERE sku_code = '" + skuCode
                    + "')");
        }

        // 是否加入个人产品库
        Integer isAddSellerProduct = bo.getIsAddSellerProduct();
        if (isAddSellerProduct != null) {
            if (isAddSellerProduct == 0) {
                lqw.apply("id in (SELECT collect_product_id FROM erp_seller_product WHERE del_flag = 0 AND seller_id = " + SecurityUtils.getUserId() + ")");
            }else if (isAddSellerProduct == 1) {
                lqw.apply("id not in (SELECT collect_product_id FROM erp_seller_product WHERE del_flag = 0 AND seller_id = " + SecurityUtils.getUserId() + ")");
            }
        }

        lqw.orderByAsc(ErpSellerCollectProduct::getDelFlag);
        lqw.orderByDesc(ErpSellerCollectProduct::getCreateTime);

        return lqw;
    }

    /**
     * 新增个人采集商品
     */
    @Override
    public Boolean insertByBo(ErpSellerCollectProductBo bo) {
        ErpSellerCollectProduct add = BeanUtil.toBean(bo, ErpSellerCollectProduct.class);
        validEntityBeforeSave(add);

        add.setCollectUserId(SecurityUtils.getUserId());
        add.setRevision(CommonUtils.getRevision(null));

        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());

            // 获取sku的信息
            List<ErpSellerCollectProductSku> skuList = bo.getSkuList();
            // 查看是否有新增的
            skuList.stream().filter(sku -> StringUtils.isEmpty(sku.getSkuCode())).forEach(sku -> {
                sku.setSkuCode(CommonUtils.getSkuCode());
                sku.setCollectProductId(add.getId());
            });
            skuList.forEach(sku -> {
                // 判断sku是否存在
                LambdaQueryWrapper<ErpSellerCollectProductSku> lqwSku = Wrappers.lambdaQuery();
                lqwSku.eq(ErpSellerCollectProductSku::getSkuCode, sku.getSkuCode());
                lqwSku.last("limit 1");
                ErpSellerCollectProductSku selectOne = erpSellerCollectProductSkuMapper.selectOne(lqwSku);
                if (selectOne != null)
                    throw new RuntimeException("skucode重复，重复的商品id为：" + selectOne.getCollectProductId());
            });
            // 保存
            erpSellerCollectProductSkuMapper.insertBatch(skuList);

            // 修改扩展表
            ErpSellerCollectProductExpand expand = bo.getExpand();
            expand.setEditStatus(1);
            expand.setCollectProductId(add.getId());
            erpSellerCollectProductExpandMapper.insert(expand);
        }
        return flag;
    }

    /**
     * 修改个人采集商品
     */
    @Override
    public Boolean updateByBo(ErpSellerCollectProductBo bo) {

        // 获取数据库中的信息
        ErpSellerCollectProduct collectProduct = baseMapper.selectById(bo.getId());
        // 判断revision
//		if (bo.getRevision() != null && !bo.getRevision().equals(collectProduct.getRevision()))
//			return false;

        // 获取用户角色
        String roles = SecurityUtils.getRoles();
        if (roles.contains("erp-user")) { // erp
            Integer operateType = collectProduct.getOperateType();
            if (operateType.equals(3)) {
                throw new RuntimeException("商品已被平台编辑，不能修改");
            }
        }

        ErpSellerCollectProduct update = BeanUtil.toBean(bo, ErpSellerCollectProduct.class);
        update.setRevision(CommonUtils.getRevision(collectProduct.getRevision()));
        validEntityBeforeSave(update);
        boolean bool = baseMapper.updateById(update) > 0;

        // sku模块，后保存
        if (bool) {
            // 先删除
            erpSellerCollectProductSkuMapper.delete(new LambdaQueryWrapper<ErpSellerCollectProductSku>()
                    .eq(ErpSellerCollectProductSku::getCollectProductId, bo.getId()));
            // 获取sku的信息
            List<ErpSellerCollectProductSku> skuList = bo.getSkuList();
            // 查看是否有新增的
            skuList.stream().filter(sku -> StringUtils.isEmpty(sku.getSkuCode())).forEach(sku -> {
                sku.setSkuCode(CommonUtils.getSkuCode());
                sku.setCollectProductId(update.getId());
            });
            skuList.forEach(sku -> {
                // 判断sku是否存在
                LambdaQueryWrapper<ErpSellerCollectProductSku> lqwSku = Wrappers.lambdaQuery();
                lqwSku.eq(ErpSellerCollectProductSku::getSkuCode, sku.getSkuCode());
                lqwSku.last("limit 1");
                ErpSellerCollectProductSku selectOne = erpSellerCollectProductSkuMapper.selectOne(lqwSku);
                if (selectOne != null) {
//                    throw new RuntimeException("skucode重复，重复的商品id为：" + selectOne.getCollectProductId());
                    sku.setSkuCode(CommonUtils.getSkuCode());
                }
            });
            // 保存
            erpSellerCollectProductSkuMapper.insertBatch(skuList);

            // 修改扩展表
            ErpSellerCollectProductExpand expand = bo.getExpand();
            expand.setEditStatus(1);
            LambdaUpdateWrapper<ErpSellerCollectProductExpand> luw = new LambdaUpdateWrapper<>();
            luw.set(expand.getBrandId() == null, ErpSellerCollectProductExpand::getBrandId, null);
            luw.eq(ErpSellerCollectProductExpand::getId, expand.getId());
            erpSellerCollectProductExpandMapper.update(expand, luw);

//            TODO 待改为内部类调用
//            erpCollectProductFreightTaskService.refresh(collectProduct.getId(), 1);
            iErpCollectProductTranslateTaskService.refresh(collectProduct.getId(), 1);

        }

        updateProductUrl(collectProduct.getId());
        // 添加到翻译
//		iErpCollectProductTranslateTaskService.refresh(collectProduct.getId());
        return bool;
    }

    @Override
    public Boolean staging(ErpSellerCollectProductBo bo) {
        boolean bool = true;
        if (bo.getId() == null) { // 新增暂存
            ErpSellerCollectProduct add = BeanUtil.toBean(bo, ErpSellerCollectProduct.class);
            validEntityBeforeSave(add);

            add.setCollectUserId(SecurityUtils.getUserId());
            add.setRevision(CommonUtils.getRevision(null));
            bool = baseMapper.insert(add) > 0;
            if (bool) {
                bo.setId(add.getId());

                // 获取sku的信息
                List<ErpSellerCollectProductSku> skuList = bo.getSkuList();
                // 查看是否有新增的
                skuList.stream().filter(sku -> StringUtils.isEmpty(sku.getSkuCode())).forEach(sku -> {
                    sku.setSkuCode(CommonUtils.getSkuCode());
                    sku.setCollectProductId(add.getId());
                });
                skuList.forEach(sku -> {
                    // 判断sku是否存在
                    LambdaQueryWrapper<ErpSellerCollectProductSku> lqwSku = Wrappers.lambdaQuery();
                    lqwSku.eq(ErpSellerCollectProductSku::getSkuCode, sku.getSkuCode());
                    lqwSku.last("limit 1");
                    ErpSellerCollectProductSku selectOne = erpSellerCollectProductSkuMapper.selectOne(lqwSku);
                    if (selectOne != null) {
//                        throw new RuntimeException("skucode重复，重复的商品id为：" + selectOne.getCollectProductId());
                        sku.setSkuCode(CommonUtils.getSkuCode());
                    }
                });
                // 保存
                erpSellerCollectProductSkuMapper.insertBatch(skuList);

                // 修改扩展表
                ErpSellerCollectProductExpand expand = bo.getExpand();
                expand.setEditStatus(0); // 未编辑成功状态
                expand.setCollectProductId(add.getId());
                erpSellerCollectProductExpandMapper.insert(expand);

            }
        } else { // 修改暂存
            // 获取数据库中的信息
            ErpSellerCollectProduct collectProduct = baseMapper.selectById(bo.getId());
            // 判断revision
//			if (bo.getRevision() != null && !bo.getRevision().equals(collectProduct.getRevision()))
//				return false;

            // 获取用户角色
            String roles = SecurityUtils.getRoles();
            if (roles.contains("erp-user")) { // erp
                Integer operateType = collectProduct.getOperateType();
                if (operateType.equals(3)) {
                    throw new RuntimeException("商品已被平台编辑，不能修改");
                }
            }

            ErpSellerCollectProduct update = BeanUtil.toBean(bo, ErpSellerCollectProduct.class);
            update.setRevision(CommonUtils.getRevision(collectProduct.getRevision()));
            validEntityBeforeSave(update);
            bool = baseMapper.updateById(update) > 0;

            // sku模块，后保存
            if (bool) {
                // 先删除
                erpSellerCollectProductSkuMapper.delete(new LambdaQueryWrapper<ErpSellerCollectProductSku>()
                        .eq(ErpSellerCollectProductSku::getCollectProductId, bo.getId()));
                // 获取sku的信息
                List<ErpSellerCollectProductSku> skuList = bo.getSkuList();
                // 查看是否有新增的
                skuList.stream().filter(sku -> StringUtils.isEmpty(sku.getSkuCode())).forEach(sku -> {
                    sku.setSkuCode(CommonUtils.getSkuCode());
                    sku.setCollectProductId(update.getId());
                });
                skuList.forEach(sku -> {
                    // 判断sku是否存在
                    LambdaQueryWrapper<ErpSellerCollectProductSku> lqwSku = Wrappers.lambdaQuery();
                    lqwSku.eq(ErpSellerCollectProductSku::getSkuCode, sku.getSkuCode());
                    lqwSku.last("limit 1");
                    ErpSellerCollectProductSku selectOne = erpSellerCollectProductSkuMapper.selectOne(lqwSku);
                    if (selectOne != null) {
//                    	throw new RuntimeException("skucode重复，重复的商品id为：" + selectOne.getCollectProductId());
                        sku.setSkuCode(CommonUtils.getSkuCode());
                    }
                });
                // 保存
                erpSellerCollectProductSkuMapper.insertBatch(skuList);

                // 修改扩展表
                ErpSellerCollectProductExpand expand = bo.getExpand();
                LambdaUpdateWrapper<ErpSellerCollectProductExpand> luw = new LambdaUpdateWrapper<>();
                luw.set(expand.getBrandId() == null, ErpSellerCollectProductExpand::getBrandId, null);
                luw.eq(ErpSellerCollectProductExpand::getId, expand.getId());
                erpSellerCollectProductExpandMapper.update(expand, luw);
                erpSellerCollectProductExpandMapper.updateById(expand);

                // 获取编辑状态
                Integer editStatus = expand.getEditStatus();
                if (editStatus.equals(1)) {
                    // 重新运费试算
                    //            TODO 待改为内部类调用
//                    erpCollectProductFreightTaskService.refresh(bo.getId(), 1);
                    // 重新翻译
                    iErpCollectProductTranslateTaskService.refresh(bo.getId(), 1);
                }
            }
        }
        return bool;
    }

    @Override
    public Integer updateUploadTestStatus(Long collectProductId) {
        ErpSellerCollectProductExpand expand = erpSellerCollectProductExpandMapper
                .selectOne(new LambdaQueryWrapper<ErpSellerCollectProductExpand>()
                        .eq(ErpSellerCollectProductExpand::getCollectProductId, collectProductId));
        expand.setIsUploadTest(1);
        if (erpSellerCollectProductExpandMapper.updateById(expand) == 1) {
            return 1;
        } else {
            return 0;
        }
    }

    //	@Async
    public void updateProductUrl(Long collectProductId) {
        ErpSellerCollectProduct collectProduct = baseMapper.selectById(collectProductId);
        collectProduct.setMarketing(urlsToOssUrls(collectProduct.getMarketing()));
        collectProduct.setImageURLs(urlsToOssUrls(collectProduct.getImageURLs()));
        collectProduct.setWhite(urlsToOssUrls(collectProduct.getWhite()));
        collectProduct.setDetailImg(urlsToOssUrls(collectProduct.getDetailImg()));
        baseMapper.updateById(collectProduct);

        List<ErpSellerCollectProductSku> erpCollectProductSkus = erpSellerCollectProductSkuMapper
                .selectList(Wrappers.lambdaQuery(new ErpSellerCollectProductSku())
                        .eq(ErpSellerCollectProductSku::getCollectProductId, collectProduct.getId()));
        erpCollectProductSkus.forEach(erpCollectProductSku -> {
            erpCollectProductSku.setSkuImage(urlsToOssUrls(erpCollectProductSku.getSkuImage()));
            erpSellerCollectProductSkuMapper.updateById(erpCollectProductSku);
        });
    }

    private String urlsToOssUrls(String urls) {
        if (Strings.isBlank(urls)) {
            return urls;
        }
        String[] urlArr = urls.split(";");
        List<String> urlList = new ArrayList<>();
        for (String url : urlArr) {
            if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("temp-product")) {
                if (url.contains("?")) {
                    url = url.substring(0, url.lastIndexOf("?"));
                }
                if (url.startsWith("temp-product")) {
                    url = "https:/file.pbb2c.com/" + url;
                }
                OssUrlDto dto = new OssUrlDto();
                dto.setOldUrl(url);
                R<Object> returnObj = remoteFileService.uploadUrl(dto);
                if (returnObj.getCode() != 200) {
                    return returnObj.getMsg();
                }
                String toJSONString = JSONObject.toJSONString(returnObj.getData());
                SysOss oss = JSONObject.parseObject(toJSONString, SysOss.class);
                urlList.add(oss == null ? url : oss.getUrl());
            } else {
                urlList.add(url);
            }
        }
        return String.join(";", urlList);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpSellerCollectProduct entity) {
        // TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除个人采集商品
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }

        LambdaUpdateWrapper<ErpSellerCollectProductExpand> luw = Wrappers.lambdaUpdate();
        luw.set(ErpSellerCollectProductExpand::getProductStatus, 0); // 下架
        luw.in(ErpSellerCollectProductExpand::getCollectProductId, ids);
        erpSellerCollectProductExpandMapper.update(null, luw);

        LambdaUpdateWrapper<ErpSellerCollectProduct> luw1 = Wrappers.lambdaUpdate();
        luw1.set(ErpSellerCollectProduct::getDelFlag, 2); // 已删除
        luw1.in(ErpSellerCollectProduct::getId, ids);
        baseMapper.update(null, luw1);

//		baseMapper.deleteBatchIds(ids);
//		erpSellerCollectProductSkuMapper.delete(new LambdaQueryWrapper<ErpSellerCollectProductSku>()
//				.in(ErpSellerCollectProductSku::getCollectProductId, ids));
//		erpSellerCollectProductExpandMapper.delete(new LambdaQueryWrapper<ErpSellerCollectProductExpand>()
//				.in(ErpSellerCollectProductExpand::getCollectProductId, ids));
        return true;
    }

    @Override
    public R<Object> publishBatch(List<Long> ids) {
        for (Long sellerCollectProId : ids) {
            publish(sellerCollectProId);
        }
        return R.ok();
    }

    @Override
    public R<Object> publish(Long sellerCollectProId) {

        // 判断是否已经刊登到个人产品库
        ErpSellerProduct sellerProduct = erpSellerProductMapper.selectOne(
                new LambdaQueryWrapper<ErpSellerProduct>().eq(ErpSellerProduct::getCollectProductId, sellerCollectProId)
                        .eq(ErpSellerProduct::getSellerId, SecurityUtils.getUserId()).last("limit 1"));
        if (sellerProduct != null)
            return R.fail("个人产品库已有该商品，不能重复刊登");

        // 刊登以前再次修改一下图片
//		updateProductUrl(sellerCollectProId);

        ErpSellerCollectProduct erpCollectProduct = baseMapper.selectById(sellerCollectProId);
//		// 获取sku
//		List<ErpSellerCollectProductSku> productVoSkus = erpSellerCollectProductSkuMapper
//				.selectList(new LambdaQueryWrapper<ErpSellerCollectProductSku>()
//						.eq(ErpSellerCollectProductSku::getCollectProductId, sellerCollectProId));
//
        // 获取产品扩展表
        ErpSellerCollectProductExpand collectProductExpand = erpSellerCollectProductExpandMapper
                .selectOne(new LambdaQueryWrapper<ErpSellerCollectProductExpand>()
                        .eq(ErpSellerCollectProductExpand::getCollectProductId, sellerCollectProId));

        //判断是否包含2.0标签
//        ErpProductClassify classify = erpProductClassifyMapper.selectOne(
//                new LambdaQueryWrapper<ErpProductClassify>()
//                        .eq(ErpProductClassify::getCode,"2.0qqby")
//        );
        String classifyLabel = collectProductExpand.getClassifyLabel();
        if (StringUtils.isNotEmpty(classifyLabel) && classifyLabel.contains("1719179918137212929")) {

        } else {
            // 判断是否符合条件
            if (collectProductExpand.getEditStatus().equals(1)
                    && collectProductExpand.getIsFreight().equals(3)
                    && (collectProductExpand.getIsUploadTest().equals(2) || collectProductExpand.getIsUploadTest().equals(5))
                    && (collectProductExpand.getIsTranslate().equals(3) || collectProductExpand.getIsTranslate().equals(4))
            ) {

            } else {
                return R.fail("进度栏有未完成的项，请编辑后再刊登");
            }
        }


        // 复制
//		ErpCollectProduct collectProduct = new ErpCollectProduct();
//		BeanUtils.copyProperties(erpCollectProduct, collectProduct);
//		collectProductMapper.insertOrUpdate(collectProduct);
//
//		// 先删除
//		collectProductExpandMapper.delete(new LambdaQueryWrapper<ErpCollectProductExpand>()
//				.eq(ErpCollectProductExpand::getCollectProductId, sellerCollectProId));
//		ErpCollectProductExpand expand = new ErpCollectProductExpand();
//		BeanUtils.copyProperties(collectProductExpand, expand);
//		expand.setCollectProductId(collectProduct.getId());
//		expand.setIsUploadTest(0); // 设置为未测试
//		expand.setProductStatus(0); // 设置为未发布
//		collectProductExpandMapper.insert(expand);
//
//		collectProductSkuMapper.delete(new LambdaQueryWrapper<ErpCollectProductSku>()
//				.eq(ErpCollectProductSku::getCollectProductId, sellerCollectProId));
//
//		for (ErpSellerCollectProductSku erpSellerCollectProductSku : productVoSkus) {
//			ErpCollectProductSku sku = new ErpCollectProductSku();
//			BeanUtils.copyProperties(erpSellerCollectProductSku, sku);
//			sku.setCollectProductId(collectProduct.getId());
//			collectProductSkuMapper.insert(sku);
//		}

//		// 保存产品成本记录
//        String classifyLabel = collectProductExpand.getClassifyLabel();
        if (StringUtils.isNotEmpty(classifyLabel) && classifyLabel.contains("1719179918137212929")) {

            // 判断是否已经翻译
            if (!collectProductExpand.getIsTranslate().equals(3)) {
                String customAttributes = erpCollectProduct.getCustomAttributes();
                // 翻译一下
                List<Dict> reslist = new ArrayList<Dict>();
                List<Dict> cusList = JsonUtils.parseArrayMap(customAttributes);
                for (Dict parseMap : cusList) {
                    String attr_name_id = parseMap.get("attr_name_id") + "";
                    if (attr_name_id.equals("-1"))
                        continue;

                    Object attr_value_id = parseMap.get("attr_value_id");
                    Object attr_value_ = parseMap.get("attr_value");
                    if (attr_value_id == null && attr_value_ == null)
                        continue;
                    if (attr_value_id != null && attr_value_id.toString().contains("[]"))
                        continue;
                    if (attr_value_id != null && attr_value_id.toString().isEmpty())
                        continue;

                    String attr_name = (String) parseMap.get("attr_name");
                    String attr_value = (String) parseMap.get("attr_value");
                    String attr_name_new = ChatGptUtils.translate(attr_name);
                    parseMap.put("attr_name", attr_name_new);
                    String attr_value_new = ChatGptUtils.translate(attr_value);
                    parseMap.put("attr_value", attr_value_new);
                    reslist.add(parseMap);
                }
                String customAttributesNew = JsonUtils.toJsonString(reslist);

                erpCollectProduct.setCustomAttributes(customAttributesNew);
                baseMapper.updateById(erpCollectProduct);
            }

            // 判断是否已经运费试算
            if (!collectProductExpand.getIsFreight().equals(3)) {

                // 获取sku
                List<ErpSellerCollectProductSku> skuList = erpSellerCollectProductSkuMapper
                        .selectList(new LambdaQueryWrapper<ErpSellerCollectProductSku>()
                                .eq(ErpSellerCollectProductSku::getCollectProductId, sellerCollectProId));

                // 保存运费为0，保存全球成本
                List<Object> list = new ArrayList<Object>();

                // 获取区域定价国家
                List<ErpProductArea> selectList = erpProductAreaMapper.selectList();
                for (ErpProductArea erpProductArea : selectList) {

                    String areaNo = erpProductArea.getAreaNo();

                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("shiptoCountry", areaNo);
                    if (areaNo.equals("GB"))
                        map.put("shiptoCountry", "UK");

                    Map<String, Double> skuMap = new HashMap<String, Double>();
                    for (ErpSellerCollectProductSku erpCollectProductSku : skuList) {
                        String skuPropertyIds = erpCollectProductSku.getSkuPropertyIds();
                        skuMap.put(skuPropertyIds, 0d);
                    }

                    map.put("absoluteQuoteMap", skuMap);
                    list.add(map);
                }

                collectProductExpand.setFreightMap(JsonUtils.toJsonString(list));
                erpSellerCollectProductExpandMapper.updateById(collectProductExpand);

                // chengben
                Map<String, BigDecimal> skuMap = new HashMap<>();
                skuList.forEach(sku -> skuMap.put(sku.getSkuPropertyIds(), new BigDecimal(sku.getSkuPrice()).multiply(new BigDecimal("1.1"))));

                Map<String, Map<String, BigDecimal>> skuPriceMap = new HashMap<>();

                String freightMap = collectProductExpand.getFreightMap();
                List<Dict> freightMapList = JsonUtils.parseArrayMap(freightMap);

                // 获取运费，修改金额
                for (Dict dict : freightMapList) {
                    Map<String, Object> absoluteQuoteMap = (Map) dict.get("absoluteQuoteMap");
                    for (String key : absoluteQuoteMap.keySet()) {
                        BigDecimal amount = skuMap.get(key);

                        if (skuPriceMap.containsKey(key)) {
                            Map<String, BigDecimal> map1 = skuPriceMap.get(key);
                            map1.put(dict.getStr("shiptoCountry"), amount);
                        } else {
                            Map<String, BigDecimal> map1 = new HashMap<String, BigDecimal>();
                            map1.put(dict.getStr("shiptoCountry"), amount);
                            skuPriceMap.put(key, map1);
                        }
                    }
                }

                List<ErpCollectProductSkuPrice> skuPriceList = new ArrayList<>();
                List<String> skucodeList = new ArrayList<String>();
                for (ErpSellerCollectProductSku erpCollectProductSku : skuList) {

                    skucodeList.add(erpCollectProductSku.getSkuCode());

                    String skuPropertyIds = erpCollectProductSku.getSkuPropertyIds();

                    // 获取sku
                    BigDecimal skuPrice = skuMap.get(skuPropertyIds);

                    ErpCollectProductSkuPrice collectProductSkuPrice = new ErpCollectProductSkuPrice();

                    collectProductSkuPrice.setCollectProductId(sellerCollectProId);
                    collectProductSkuPrice.setSkuCode(erpCollectProductSku.getSkuCode());
                    collectProductSkuPrice.setSkuPrice(skuPrice.toString());
                    Map<String, BigDecimal> map = skuPriceMap.get(skuPropertyIds);
                    collectProductSkuPrice.setAbsoluteQuoteMap(JsonUtils.toJsonString(map));

                    collectProductSkuPrice.setOriginalSkuPrice(skuPrice.toString());

                    // 获取支持的全球国家
//                    List<ErpProductFreight> countryList = iErpProductFreightService.countryList();
//
//                    Map<String, Double> globalFreightMap = new HashMap<>();
//                    Map<String, BigDecimal> globalQuoteMap = new HashMap<>();
//
//                    for (ErpProductFreight freight : countryList) {
//
//                        Double priceCalculator = 0d;
//                        String countryCode = freight.getCountryCode();
//
//                        if (countryCode.equals("GB"))
//                            countryCode = "UK";
//                        globalFreightMap.put(countryCode, priceCalculator);
//
//                        // 计算区域定价
//                        BigDecimal globalQuote = skuPrice;
//                        globalQuoteMap.put(countryCode, globalQuote);
//                    }

//                    collectProductSkuPrice.setFreightMap(JsonUtils.toJsonString(globalFreightMap));
//                    collectProductSkuPrice.setGlobalQuoteMap(JsonUtils.toJsonString(globalQuoteMap));
                    skuPriceList.add(collectProductSkuPrice);
                }
                // 先删除
                collectProductSkuPriceMapper.delete(new LambdaQueryWrapper<ErpCollectProductSkuPrice>()
                        .in(ErpCollectProductSkuPrice::getCollectProductId, sellerCollectProId));
                // 在添加
                collectProductSkuPriceMapper.insertBatch(skuPriceList);
            }

        } else {
            iErpCollectProductSkuPriceService.saveSkuPrice(sellerCollectProId);
        }
        // 伪上架
        iErpCollectProductService.updateSkuProperty(sellerCollectProId);

        // 刊登到个人产品库
        iErpCollectProductService.publish(sellerCollectProId, SecurityUtils.getUserId(), 0, 0, SecurityUtils.getRoles(),null);

        // 如果是2.0商品，将上架状态修改为已上架 by zj 240108
        if (StringUtils.isNotEmpty(classifyLabel) && classifyLabel.contains("1719179918137212929")) {
            // 修改上架状态
            erpCollectProductExpandService.updateProductStatusById(collectProductExpand.getId(), null, 1);
        }

        return R.ok("商品发布中，请到个人产品库查看发布商品");
    }

    @Override
    public R<Object> ignoreTest(Long sellerCollectProId) {
        // 获取产品扩展表
        ErpSellerCollectProductExpand collectProductExpand = erpSellerCollectProductExpandMapper
                .selectOne(new LambdaQueryWrapper<ErpSellerCollectProductExpand>()
                        .eq(ErpSellerCollectProductExpand::getCollectProductId, sellerCollectProId));

        collectProductExpand.setIsUploadTest(5);
        erpSellerCollectProductExpandMapper.updateById(collectProductExpand);
        return R.ok("操作成功");
    }

    @Override
    public void updateCateGoryProById(Long proId) {
        try {
            // 获取扩展类和sku列表
            ErpSellerCollectProductExpand expand = erpSellerCollectProductExpandMapper
                    .selectOne(new LambdaQueryWrapper<ErpSellerCollectProductExpand>()
                            .eq(ErpSellerCollectProductExpand::getCollectProductId, proId).last(" limit 1 "));

            List<ErpSellerCollectProductSku> skuList = erpSellerCollectProductSkuMapper
                    .selectList(new LambdaQueryWrapper<ErpSellerCollectProductSku>()
                            .eq(ErpSellerCollectProductSku::getCollectProductId, proId));

            // 判断是否是多规格，不是就跳过
            ErpSellerCollectProductSku erpCollectProductSku = skuList.get(0);
            String skuPropertyIds = erpCollectProductSku.getSkuPropertyIds();
            if (!skuPropertyIds.contains(";"))
                return;

            // 多规格合并为单规格
            String skuProperty = expand.getSkuProperty();

            // 解析合并
            Map<String, Long> map = new HashMap<>();

            Long value = 30000l;

            List<Dict> propertyList = JsonUtils.parseArrayMap(skuProperty);
            Dict dict = propertyList.get(0);
            List<HashMap<String, Object>> oneValue = (List<HashMap<String, Object>>) dict.get("list");

            List<HashMap<String, Object>> res = new ArrayList<>();
            for (int i = 1; i < propertyList.size(); i++) {
                Dict dict1 = propertyList.get(i);
                List<HashMap<String, Object>> otherValue = (List<HashMap<String, Object>>) dict1.get("list");

                // 合并
                for (HashMap<String, Object> map1 : oneValue) {
                    String name = (String) map1.get("name");
                    Object value1 = map1.get("value");

                    for (HashMap<String, Object> map2 : otherValue) {

                        HashMap<String, Object> newHashMap = new HashMap<>();

                        String name2 = (String) map2.get("name");

                        String nameres = name + " " + name2;
                        newHashMap.put("name", nameres);
                        newHashMap.put("value", value);

                        Object value2 = map2.get("value");

                        String key = value1 + "-" + value2;
                        map.put(key, value);

                        value++;

                        res.add(newHashMap);
                    }
                }
            }

            dict.put("list", res);
            propertyList = new ArrayList<Dict>();
            propertyList.add(dict);
            expand.setSkuProperty(JsonUtils.toJsonString(propertyList));

            // 修改sku
            for (ErpSellerCollectProductSku sku : skuList) {

                String nameId = "";
                String valueId = "";

                // 获取sku属性
                String skuPropertyIds2 = sku.getSkuPropertyIds();
                String[] split = skuPropertyIds2.split(";");
                for (int i = 0; i < split.length; i++) {
                    String[] split2 = split[i].split(":");
                    if (i == 0) {
                        nameId = split2[0];
                    }
                    valueId = valueId + split2[1] + "-";
                }

                valueId = valueId.substring(0, valueId.length() - 1);

                // 获取新的id
                Long long1 = map.get(valueId);

                String newSkuPropertyIds = nameId + ":" + long1;
                sku.setSkuPropertyIds(newSkuPropertyIds);

            }

            // 更新扩展表和sku表
            erpSellerCollectProductExpandMapper.updateById(expand);
            erpSellerCollectProductSkuMapper.updateBatchById(skuList);

            // 获取编辑状态
            Integer editStatus = expand.getEditStatus();
            if (editStatus.equals(1)) {
                // 重新运费试算
                // TODO 待改为内部类调用
//                erpCollectProductFreightTaskService.refresh(proId, 1);
                // 重新翻译
                iErpCollectProductTranslateTaskService.refresh(proId, 1);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void copyToPublic() {
        // 获取个人采集库有，公共采集库没有的
        List<ErpSellerCollectProduct> list = baseMapper.selectCopyToPublicPro();

        List<Long> idList = new ArrayList<Long>();

        for (ErpSellerCollectProduct erpSellerCollectProduct : list) {

            Long sellerCollectProId = erpSellerCollectProduct.getId();
            try {

                // 获取sku
                List<ErpSellerCollectProductSku> productVoSkus = erpSellerCollectProductSkuMapper
                        .selectByProId(sellerCollectProId);

                // 获取产品扩展表
                ErpSellerCollectProductExpand collectProductExpand = erpSellerCollectProductExpandMapper
                        .selectByProId(sellerCollectProId);

                // 复制
                ErpCollectProduct collectProduct = new ErpCollectProduct();
                BeanUtils.copyProperties(erpSellerCollectProduct, collectProduct);
                collectProductMapper.insertOrUpdate(collectProduct);

                ErpCollectProductExpand expand = new ErpCollectProductExpand();
                BeanUtils.copyProperties(collectProductExpand, expand);
                expand.setCollectProductId(collectProduct.getId());
                collectProductExpandMapper.insert(expand);

                for (ErpSellerCollectProductSku erpSellerCollectProductSku : productVoSkus) {
                    ErpCollectProductSku sku = new ErpCollectProductSku();
                    BeanUtils.copyProperties(erpSellerCollectProductSku, sku);
                    sku.setCollectProductId(collectProduct.getId());
                    collectProductSkuMapper.insert(sku);
                }
            } catch (Exception e) {
                idList.add(sellerCollectProId);
            }
        }
        System.out.println(idList);
    }

    /**
     * 同步平台内商品信息
     *
     * @return
     */
//	@Override
//	public List<Long> syncProErp(Long proId) {
//
//		List<Long> resList = new ArrayList<>();
//
//		ErpSellerCollectProduct collectProduct = baseMapper.selectById(proId);
//
//		ErpSellerCollectProductExpand expand = erpSellerCollectProductExpandMapper
//				.selectOne(new LambdaQueryWrapper<ErpSellerCollectProductExpand>()
//						.eq(ErpSellerCollectProductExpand::getCollectProductId, proId).last(" limit 1 "));
//
//		List<ErpSellerCollectProductSku> skuList = erpSellerCollectProductSkuMapper
//				.selectList(new LambdaQueryWrapper<ErpSellerCollectProductSku>()
//						.eq(ErpSellerCollectProductSku::getCollectProductId, proId));
//
//		// 计算区域定价
//		Map<String, BigDecimal> skuMap = new HashMap<>();
//		skuList.forEach(sku -> skuMap.put(sku.getSkuPropertyIds(),
//				new BigDecimal(sku.getSkuPrice()).multiply(new BigDecimal(1.1))));
//
//		Double min = null;
//		Double max = null;
//
//		String freightMap = expand.getFreightMap();
//		List<Dict> freightMapList = JsonUtils.parseArrayMap(freightMap);
//
//		// 获取运费，修改金额
//		for (Dict dict : freightMapList) {
//			Map<String, Object> absoluteQuoteMap = (Map) dict.get("absoluteQuoteMap");
//			String shiptoCountry = (String) dict.get("shiptoCountry");
//			for (String key : absoluteQuoteMap.keySet()) {
//				BigDecimal amount = new BigDecimal(absoluteQuoteMap.get(key).toString());
//
//				// 获取sku
//				BigDecimal skuPrice = skuMap.get(key);
//
//				// 计算最终价格
//				amount = skuPrice.add(amount).setScale(2, BigDecimal.ROUND_HALF_UP);
//				Double res = amount.doubleValue();
//				absoluteQuoteMap.put(key, res);
//				if (shiptoCountry.equals("US")) {
//					if (min == null || res < min)
//						min = res;
//					if (max == null || res > max)
//						max = res;
//				}
//
//			}
//		}
//
//		// 获取完成的区域定价
//		String absoluteQuoteMap = JsonUtils.toJsonString(freightMapList);
//		expand.setAbsoluteQuoteMap(absoluteQuoteMap);
//
//		// 修改商品的价格
//		collectProduct.setId(proId);
//		collectProduct.setProductPrice(min.equals(max) ? min + "" : min + "-" + max);
//		baseMapper.updateById(collectProduct);
//
//		// 保存
//		erpSellerCollectProductSkuMapper.updateBatchById(skuList);
//		erpSellerCollectProductExpandMapper.updateById(expand);
//
//		Map<String, BigDecimal> sellerProductSkuPriceMap = new HashMap<>();
//
//		Map<String, BigDecimal> skuPriceMap = new HashedMap<>();
//		String freightMap1 = expand.getFreightMap();
//		List<Dict> freightMapList1 = JsonUtils.parseArrayMap(freightMap1);
//
//		// 获取运费，修改金额
//		for (Dict dict : freightMapList1) {
//			Map<String, Object> absoluteQuoteMap1 = (Map) dict.get("absoluteQuoteMap");
//			for (String key : absoluteQuoteMap1.keySet()) {
//				BigDecimal amount = new BigDecimal(absoluteQuoteMap1.get(key).toString());
//
//				// 添加sku价格
//				if (skuPriceMap.containsKey(key)) {
//					BigDecimal price = skuPriceMap.get(key);
//					if (price.compareTo(amount) == 1)
//						skuPriceMap.put(key, amount);
//				} else {
//					skuPriceMap.put(key, amount);
//				}
//			}
//		}
//
//		for (ErpSellerCollectProductSku erpCollectProductSkuVo : skuList) {
//			String skuPropertyIds = erpCollectProductSkuVo.getSkuPropertyIds();
//			if (skuPriceMap.containsKey(skuPropertyIds)) {
//				BigDecimal minPrice = skuPriceMap.get(skuPropertyIds);
//
//				// 获取sku
//				BigDecimal skuPrice = new BigDecimal(erpCollectProductSkuVo.getSkuPrice());
//				skuPrice = skuPrice.multiply(new BigDecimal(1.1));
//
//				// 计算最终价格
//				BigDecimal amount = skuPrice.add(minPrice.multiply(new BigDecimal(1.5))).setScale(2,
//						BigDecimal.ROUND_HALF_UP);
//
//				sellerProductSkuPriceMap.put(skuPropertyIds, amount);
//			}
//		}
//
//		// 根据商品id获取全部的个人产品库的品，一般应该只有一个
//		List<ErpSellerProduct> sellerProList = erpSellerProductMapper.selectList(
//				new LambdaQueryWrapper<ErpSellerProduct>().eq(ErpSellerProduct::getCollectProductId, proId));
//		for (ErpSellerProduct erpSellerProduct : sellerProList) {
//
//			Long sellerProId = erpSellerProduct.getId();
//
//			ErpSellerProductExpand erpSellerProductExpand = erpSellerProductExpandMapper
//					.selectOne(new LambdaQueryWrapper<ErpSellerProductExpand>()
//							.eq(ErpSellerProductExpand::getSellerProductId, sellerProId).last(" limit 1 "));
//
//			// 修改
//			ErpSellerProduct newErpSellerProduct = new ErpSellerProduct();
//			BeanUtils.copyProperties(collectProduct, newErpSellerProduct);
//			newErpSellerProduct.setId(sellerProId);
//			newErpSellerProduct.setSellerId(erpSellerProduct.getSellerId());
//			newErpSellerProduct.setCollectProductId(proId);
//			newErpSellerProduct.setCreateTime(erpSellerProduct.getCreateTime());
//			newErpSellerProduct.setUpdateTime(erpSellerProduct.getUpdateTime());
//			newErpSellerProduct.setCreateBy(erpSellerProduct.getCreateBy());
//			newErpSellerProduct.setUpdateBy(erpSellerProduct.getUpdateBy());
//			erpSellerProductMapper.updateById(newErpSellerProduct);
//
//			// 修改商品扩展类
//			ErpSellerProductExpand newErpSellerProductExpand = new ErpSellerProductExpand();
//			BeanUtils.copyProperties(expand, newErpSellerProductExpand);
//			newErpSellerProductExpand.setId(erpSellerProductExpand.getId());
//			newErpSellerProductExpand.setSellerProductId(sellerProId);
//			newErpSellerProductExpand.setCreateTime(erpSellerProductExpand.getCreateTime());
//			newErpSellerProductExpand.setUpdateTime(erpSellerProductExpand.getUpdateTime());
//			newErpSellerProductExpand.setCreateBy(erpSellerProductExpand.getCreateBy());
//			newErpSellerProductExpand.setUpdateBy(erpSellerProductExpand.getUpdateBy());
//			erpSellerProductExpandMapper.updateById(newErpSellerProductExpand);
//
//			// 删除sku
//			erpSellerProductSkuMapper.delete(new LambdaQueryWrapper<ErpSellerProductSku>()
//					.eq(ErpSellerProductSku::getSellerProductId, sellerProId));
//
//			// 再保存新的
//			List<ErpSellerProductSku> sellerProductSkuList1 = new ArrayList<>();
//			// 保存sku
//			for (ErpSellerCollectProductSku erpCollectProductSkuVo : skuList) {
//				ErpSellerProductSku erpSellerProductSku = new ErpSellerProductSku();
//				BeanUtils.copyProperties(erpCollectProductSkuVo, erpSellerProductSku);
//				erpSellerProductSku.setId(null);
//				erpSellerProductSku.setSellerProductId(erpSellerProduct.getId());
//				erpSellerProductSku.setCreateTime(null);
//				erpSellerProductSku.setUpdateTime(null);
//				erpSellerProductSku.setCreateBy(erpSellerProduct.getCreateBy());
//				erpSellerProductSku.setUpdateBy(erpSellerProduct.getCreateBy());
//
//				String skuPropertyIds = erpSellerProductSku.getSkuPropertyIds();
//
//				BigDecimal amount = sellerProductSkuPriceMap.get(skuPropertyIds);
//				erpSellerProductSku.setSkuPrice(amount.toString());
//
//				erpSellerProductSkuMapper.insert(erpSellerProductSku);
//				sellerProductSkuList1.add(erpSellerProductSku);
//			}
//		}
//
//		// 查询在线商品表的数据
//		List<ErpSellerStoreProduct> sellerStoreProList = erpSellerStoreProductMapper.selectList(
//				new LambdaQueryWrapper<ErpSellerStoreProduct>().eq(ErpSellerStoreProduct::getCollectProductId, proId));
//
//		// 在线商品表信息修改
//		for (ErpSellerStoreProduct erpSellerStoreProduct : sellerStoreProList) {
//
//			Long sellerStoreId = erpSellerStoreProduct.getId();
//			Long storeId = erpSellerStoreProduct.getStoreId();
//
//			// 获取扩展表
//			ErpSellerStoreProductExpand sellerStoreProductExpand = erpSellerStoreProductExpandMapper
//					.selectOne(new LambdaQueryWrapper<ErpSellerStoreProductExpand>()
//							.eq(ErpSellerStoreProductExpand::getSellerStoreProductId, sellerStoreId));
//
//			// 计算价格
//			Map<String, Object> absoluteQuoteMap1 = iErpSellerStoreProductService.countPrice(
//					expand.getAbsoluteQuoteMap(), sellerStoreProductExpand.getPriceAdjustmentMethod(),
//					sellerStoreProductExpand.getReadjustPricesType(), sellerStoreProductExpand.getReadjustPrices(),
//					sellerStoreProductExpand.getTemplateId(), collectProduct.getProductPrice());
//
//			ErpSellerStoreProduct sellerStoreProduct = new ErpSellerStoreProduct();
//			BeanUtils.copyProperties(collectProduct, sellerStoreProduct);
//			sellerStoreProduct.setId(erpSellerStoreProduct.getId());
//			sellerStoreProduct.setSellerProductId(erpSellerStoreProduct.getSellerProductId());
//			sellerStoreProduct.setStoreId(storeId);
//			sellerStoreProduct.setCreateTime(erpSellerStoreProduct.getCreateTime());
//			sellerStoreProduct.setUpdateTime(erpSellerStoreProduct.getUpdateTime());
//			sellerStoreProduct.setCreateBy(erpSellerStoreProduct.getCreateBy());
//			sellerStoreProduct.setUpdateBy(erpSellerStoreProduct.getUpdateBy());
//			sellerStoreProduct.setCustomAttributes(erpSellerStoreProduct.getCustomAttributes());
//
//			sellerStoreProduct.setProductPrice((String) absoluteQuoteMap1.get("productPrice"));
//			erpSellerStoreProductMapper.updateById(sellerStoreProduct);
//
//			// 匹配运费模板
//			// 获取系统预制的运费模板标识
//			Integer settingFreightTemplateId = expand.getTemplateId();
//			String mbName = dictService.getDictValue("erp_freight_template", settingFreightTemplateId + "");
//
//			// 判断用哪个运费模板
//			if (StringUtils.isNotEmpty(mbName)) {
//				// 根据店铺id和固定模板名字获取运费模板id
//				LambdaQueryWrapper<ErpSellerStoreFreightTemplate> freLqw = new LambdaQueryWrapper<ErpSellerStoreFreightTemplate>();
//				freLqw.eq(ErpSellerStoreFreightTemplate::getSellerStoreId, storeId);
//				freLqw.like(ErpSellerStoreFreightTemplate::getTemplateName, mbName);
//				freLqw.last("limit 1");
//				ErpSellerStoreFreightTemplate freightTemplate = erpSellerStoreFreightTemplateMapper.selectOne(freLqw);
//				if (freightTemplate == null) { // 没有模板，先同步一下，防止没有同步发布失败
//					iAeProductService.getSellerStoreFreightTemplate(storeId);
//
//					// 再获取一次
//					freightTemplate = erpSellerStoreFreightTemplateMapper.selectOne(freLqw);
//				}
//				if (freightTemplate != null)
//					sellerStoreProductExpand.setFreightTemplateId(freightTemplate.getTemplateId()); // 运费模板
//			}
//			sellerStoreProductExpand.setAbsoluteQuoteMap((String) absoluteQuoteMap1.get("absoluteQuoteMapStr"));
//			// 查看运费模板是否有多个发货地
//			R<Object> freightTemplateLogisticsCompany = iAeProductService
//					.getFreightTemplateLogisticsCompany(sellerStoreProductExpand.getFreightTemplateId(), storeId);
//			if (freightTemplateLogisticsCompany.getCode() == 200) {
//				List<String> dataList = (List<String>) freightTemplateLogisticsCompany.getData();
//				if (ObjectUtils.isNotEmpty(dataList)) {
//					sellerStoreProductExpand.setOverseasWarehouse(String.join(",", dataList));
//				}
//			}
//			erpSellerStoreProductExpandMapper.updateById(sellerStoreProductExpand);
//
//			// 获取商品sku属性
//			String skuProperty = expand.getSkuProperty();
//			List<Dict> skuPropertyList = JsonUtils.parseArrayMap(skuProperty);
//
//			// 创建属性对应map
//			Map<String, String> skuPropertyMap = new HashMap<>();
//			for (Dict dict : skuPropertyList) {
//				List<Map<String, Object>> propertyList = (List<Map<String, Object>>) dict.get("list");
//				for (Map<String, Object> propertyMap : propertyList) {
//					skuPropertyMap.put(dict.getStr("value") + ":" + propertyMap.get("value"),
//							propertyMap.get("name") + "");
//				}
//			}
//
//			// 删除sku
//			erpSellerStoreProductSkuMapper.delete(new LambdaQueryWrapper<ErpSellerStoreProductSku>()
//					.eq(ErpSellerStoreProductSku::getSellerStoreProductId, sellerStoreId));
//
//			// 保存新的
//			for (ErpSellerCollectProductSku sku : skuList) {
//				ErpSellerStoreProductSku erpSellerStoreProductSku = new ErpSellerStoreProductSku();
//				BeanUtils.copyProperties(sku, erpSellerStoreProductSku);
//				erpSellerStoreProductSku.setId(null);
//				erpSellerStoreProductSku.setSellerStoreProductId(sellerStoreProduct.getId());
//				erpSellerStoreProductSku.setCreateTime(null);
//				erpSellerStoreProductSku.setUpdateTime(null);
//				erpSellerStoreProductSku.setCreateBy(erpSellerStoreProduct.getCreateBy());
//				erpSellerStoreProductSku.setUpdateBy(erpSellerStoreProduct.getCreateBy());
//				erpSellerStoreProductSku.setSkuStock(999l);
//
//				String skuPropertyIds = sku.getSkuPropertyIds();
//				BigDecimal skuPrice = sellerProductSkuPriceMap.get(skuPropertyIds);
//				BigDecimal readjustPrices = (BigDecimal) absoluteQuoteMap1.get("readjustPrices");
//				BigDecimal profitNum = (BigDecimal) absoluteQuoteMap1.get("profitNum");
//
//				// 计算价格
//				if (sellerStoreProductExpand.getPriceAdjustmentMethod().equals("0")) { // 手动
//					if (readjustPrices != null) {
//						skuPrice = skuPrice.multiply(readjustPrices).setScale(2, BigDecimal.ROUND_HALF_UP);
//					}
//				} else { // 智能定价
//					skuPrice = (skuPrice.add(profitNum)).multiply(readjustPrices).setScale(2, BigDecimal.ROUND_HALF_UP);
//				}
//				erpSellerStoreProductSku.setSkuPrice(skuPrice.toString());
//
//				String[] split = skuPropertyIds.split(";");
//
//				// 添加属性
//				List<Map<String, Object>> list = new LinkedList<Map<String, Object>>();
//				for (int i = 0; i < split.length; i++) {
//					String string2 = split[i];
//					String[] split2 = string2.split(":");
//					Map<String, Object> map = new HashMap<String, Object>();
//					if (i == 0) {
//						map.put("sku_image", erpSellerStoreProductSku.getSkuImage());
//					}
//					map.put("property_value_definition_name", skuPropertyMap.get(string2));
//					map.put("property_value_id", split2[1]);
//					map.put("sku_property_id", split2[0]);
//					list.add(map);
//
//				}
//
//				erpSellerStoreProductSku.setSkuProperty(JsonUtils.toJsonString(list));
//
//				erpSellerStoreProductSkuMapper.insert(erpSellerStoreProductSku);
//			}
//			resList.add(sellerStoreId);
//		}
//		return resList;
//	}

}
